const fs=require('fs');
const path=require('path');
const promisify=require('util').promisify;
const handlebars=require('handlebars');
const stat=promisify(fs.stat);
const readdir=promisify(fs.readdir);
// const conf=require('../config/defaultConfig');
const mime=require('./mime');
const compress=require('./compress');
const range=require('./range');
const isFresh=require('./cache');


const tplPath=path.join(__dirname,'../tpl/dir.tpl')
const source=fs.readFileSync(tplPath);
const template=handlebars.compile(source.toString())

module.exports=async function(req,res,filePath,conf){
	try{
		const stats=await stat(filePath);
		if(stats.isFile()){
			res.statusCode=200;
			const contentType=mime(filePath);
			res.setHeader('Content-type',contentType);
			if(isFresh(stats,req,res)){
				res.statusCode=304;
				res.end();
				return ;
			}

			//相应太慢
			// fs.readFile(filePath,(err,data)=>{
			// 	res.end(data);
			// });
			let rs;
			const {code,start,end}=range(stats.size,req,res);
			if(code===200){
				res.statusCode=200;
				rs=fs.createReadStream(filePath);
			}else{
				res.statusCode=206;
				rs=fs.createReadStream(filePath,{start,end});
			}
			if(filePath.match(conf.compress)){
				rs=compress(rs,req,res)
			}
			rs.pipe(res);
		}else if(stats.isDirectory()){
			const files=await readdir(filePath);
			res.statusCode=200;
			res.setHeader('Content-type','text/html');
			const dir=path.relative(conf.root,filePath);
			const data={
				tittle:path.basename(filePath),
				dir:dir?('/'+dir):'',
				files:files.map(file=>{
					return {
						file,
						icon:mime(file)
					}
				})
			}
			res.end(template(data));
			// res.end(files.join(','))
			// fs.readdir(filePath,(err,files)=>{
			//
			// })
		}
	}catch (ex){
		res.statusCode=404;
		res.setHeader('Content-type','text/plain');
		res.write(ex.toString());
		res.end('not found '+filePath);
	}
}